<!-- 问题汇总图表 -->
<template>
  <div :id='id' style='width: 100%; height: 100%'>

  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  props: {
    data: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      id: null,
      range: [0.4, 1],
      color: '21,71,163',
      myChart: null,
      colorList: ['rgba(21,71,163, 1)']
    }
  },
  watch: {
    data: {
      handler(val) {
        if (val && (Array.isArray(val) && val.length > 0)) {
          this.drawCharts()
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.init()
  },
  beforeDestory() {
    this.disposeCharts()
  },
  methods: {
    init() {
      this.id = Math.ceil(Math.random() * 10000)
    },
    buildColorList() {
      let result = this.colorList
      const item = (this.range[1] - this.range[0]) / ((this.data || [{}]).length)
      result = (this.data || []).map((x, index) => {
        return 'rgba(' + this.color + ', ' + (((this.range || [])[0] || 0) -  -(item * (index - -1))) + ')'
      })
      this.colorList = result
    },
    disposeCharts() {
      // 销毁echarts实例
      try {
        this.myChart.dispose()
        this.myChart = null
      } catch (e) {
        this.myChart = null
      }
    },
    drawCharts() {
      this.disposeCharts()
      this.buildColorList()
      // 基于准备好的dom，初始化echarts实例
      const myChart = echarts.init(document.getElementById(this.id))
      const data = this.data
      const option = {
        color: this.colorList,
        series: [
          {
            type: 'pie',
            radius: '85%',
            label: {
              formatter: function (val) {
                return ((val.data || {}).name || '-') + '\n' + ((val.data || {}).value || '-')
              }
            },
            data: data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      // 绘制图表
      myChart.setOption(option)
      this.myChart = myChart
    },
  }
}
</script>